#!/bin/bash

set -e

WLAN_IFACE="wlan0"
LAN_IFACE="eth0"

log() {
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] $1"
}

log "1. 停止 wpa_supplicant 和可能的网络管理器..."
sudo killall wpa_supplicant || true
sudo systemctl stop NetworkManager || true

log "2. 关闭 wlan0..."
sudo ip link set $WLAN_IFACE down
sleep 1
sudo ip link set $WLAN_IFACE up

log "3. 启动 hostapd..."
sudo systemctl restart hostapd

log "4. 启动 dnsmasq..."
sudo systemctl restart dnsmasq

log "5. 开启 IP 转发..."
sudo sysctl -w net.ipv4.ip_forward=1

log "6. 设置 iptables NAT 转发规则..."
sudo iptables -t nat -F
sudo iptables -F FORWARD
sudo iptables -t nat -A POSTROUTING -o $LAN_IFACE -j MASQUERADE
sudo iptables -A FORWARD -i $WLAN_IFACE -o $LAN_IFACE -j ACCEPT
sudo iptables -A FORWARD -i $LAN_IFACE -o $WLAN_IFACE -m state --state ESTABLISHED,RELATED -j ACCEPT

log "7. 检查外网连通性 (ping 8.8.8.8)..."
if ping -c 3 -I $LAN_IFACE 8.8.8.8 > /dev/null 2>&1; then
    log "✅ 热点启动成功，NAT 转发正常，设备可联网。"
else
    log "❌ 无法通过 $LAN_IFACE 上网，请检查外网连接或防火墙设置。"
fi
